package com.zys.asseter.controller;

import com.zys.asseter.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/api/files")
public class UploadController {


    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,
                                             @RequestParam("type") String type) {
        try {
            // 获取文件的原始名称和内容类型
            String fileName = file.getOriginalFilename();
            String contentType = file.getContentType();

            // 定义最大文件大小（以字节为单位）
            long maxSizeForOthers = 5 * 1024 * 1024; // 5 MB
            long maxSizeForPdfAndVideo = 90 * 1024 * 1024; // 90 MB

            // 检查文件是否为空
            if (fileName == null || fileName.isEmpty()) {
                return ResponseEntity.badRequest().body("File is empty or name is invalid.");
            }

            // 根据文件类型检查大小限制
            if ("pdf".equalsIgnoreCase(type) && contentType != null && contentType.startsWith("application/pdf")) {
                if (file.getSize() > maxSizeForPdfAndVideo) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("PDF file size exceeds the limit of 90MB.");
                }
            } else if ("video".equalsIgnoreCase(type) &&
                    (contentType != null &&
                            (contentType.startsWith("video/") || contentType.equals("application/octet-stream")))) {
                if (file.getSize() > maxSizeForPdfAndVideo) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("Video file size exceeds the limit of 90MB.");
                }
            } else {
                if (file.getSize() > maxSizeForOthers) {
                    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("File size exceeds the limit of 5MB for this type.");
                }
            }

            // 如果文件通过了所有验证，则继续处理
            fileService.store(file, type);
            return ResponseEntity.ok("File uploaded successfully");

        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to upload file: " + e.getMessage());
        }
    }
}

